//
//  WJMBProgressHUDController.m
//  JerryIos
//
//  Created by jerrywang on 2018/2/9.
//  Copyright © 2018年 王军. All rights reserved.
//

#import "WJMBProgressHUDController.h"
#import "WJCarBrand.h"
#import "WJCar.h"
#import "MBProgressHUD.h"

@interface WJMBProgressHUDController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) NSArray *carBrandArray;
@property (atomic, assign) BOOL canceled;

@end

@implementation WJMBProgressHUDController

- (NSArray *)carBrandArray {
    if (_carBrandArray == nil) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"mb_progress.plist" ofType:nil];
        NSArray *dicArray = [NSArray arrayWithContentsOfFile:path];
        
        NSMutableArray *groupArray = [NSMutableArray array];
        for (NSDictionary *dic in dicArray) {
            WJCarBrand *carBrand = [WJCarBrand carBrandWithDict:dic];
            [groupArray addObject:carBrand];
        }
        _carBrandArray = groupArray;
    }
    return _carBrandArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    // 创建NavBar
    [self setupNavBar];
}

// 创建NavBar
- (void)setupNavBar {
    //右边的按钮
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImage:[UIImage imageNamed:@"icon_share_normal"]
                                                                  highImage:[UIImage imageNamed:@"icon_share_selected"] target:self
                                                                     action:@selector(share)];
    //中间的标题
    self.navigationItem.title = @"MBProgressHUD";
    
}

-(void)share{
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.carBrandArray.count;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    WJCarBrand *carBrand = self.carBrandArray[section];
    return carBrand.title;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    WJCarBrand *carBrand = self.carBrandArray[section];
    return carBrand.carArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellId = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                      reuseIdentifier:cellId];
    }
    WJCarBrand *carBrand = self.carBrandArray[indexPath.section];
    WJCar *car = carBrand.carArray[indexPath.row];
    cell.imageView.image = [UIImage imageNamed:car.icon];
    cell.textLabel.text = car.name;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    switch (indexPath.section) {
        case 0:
            [self showProgress1:indexPath.row];
            break;
        case 1:
            [self showProgress2:indexPath.row];
            break;
        case 2:
            [self showProgress3:indexPath.row];
            break;
        case 3:
            [self showProgress4:indexPath.row];
            break;
        default:
            break;
    }
}

-(void) showProgress1:(NSInteger)row {
    switch (row) {
        case 0:{
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
            
            [self dismissAfter:hud];
            break;
        }
        case 1:{
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
            hud.label.text = NSLocalizedString(@"Loading...", @"HUD loading title");
            hud.label.font = [UIFont italicSystemFontOfSize:16.f];
            
            [self dismissAfter:hud];
            break;
        }
        case 2:{
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
            hud.label.text = NSLocalizedString(@"Loading...", @"HUD loading title");
            hud.detailsLabel.text = NSLocalizedString(@"Parsing data\n(1/1)", @"HUD title");
           
            [self dismissAfter:hud];
            break;
        }
        default:
            break;
    }
}

-(void) showProgress2:(NSInteger)row {
    switch (row) {
        case 0:{
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
            hud.mode = MBProgressHUDModeDeterminate;
            hud.label.text = NSLocalizedString(@"Loading111...", @"HUD loading title");
            
            [self dismissProgressAfter:hud];
            break;
        }
        case 1:{
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
            hud.mode = MBProgressHUDModeAnnularDeterminate;
            hud.label.text = NSLocalizedString(@"Loading222...", @"HUD loading title");
            
            [self dismissProgressAfter:hud];
            break;
        }
        case 2:{
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
            hud.mode = MBProgressHUDModeDeterminateHorizontalBar;
            hud.label.text = NSLocalizedString(@"Loading333...", @"HUD loading title");
            
            [self dismissProgressAfter:hud];
            break;
        }
        default:
            break;
    }
}

-(void) showProgress3:(NSInteger)row {
    switch (row) {
        case 0:{
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
            hud.mode = MBProgressHUDModeText;
            hud.label.text = NSLocalizedString(@"Message here!", @"HUD message title");
            // Move to bottm center.
            hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
            
            [self dismissAfter2:hud];
            break;
        }
        case 1:{
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
            hud.mode = MBProgressHUDModeCustomView;
            // Set an image view with a checkmark.
            UIImage *image = [[UIImage imageNamed:@"icon_home"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
            hud.customView = [[UIImageView alloc] initWithImage:image];
            // Looks a bit nicer if we make it square.
            hud.square = YES;
            // Optional label text.
            hud.label.text = NSLocalizedString(@"Done", @"HUD done title");
            
            [self dismissAfter2:hud];
            break;
        }
        case 2:{
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
            hud.mode = MBProgressHUDModeDeterminate;
            hud.label.text = NSLocalizedString(@"Loading...", @"HUD loading title");
            
            // Configure the button.
            [hud.button setTitle:NSLocalizedString(@"Cancel", @"HUD cancel button title") forState:UIControlStateNormal];
            [hud.button addTarget:self action:@selector(cancelWork:) forControlEvents:UIControlEventTouchUpInside];
            
            [self dismissProgressAfter:hud];
            break;
        }
        case 3:{
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
            hud.label.text = NSLocalizedString(@"Preparing...", @"HUD preparing title");
            hud.minSize = CGSizeMake(150.f, 100.f);
            
            dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
                // Do something useful in the background and update the HUD periodically.
                [self doSomeWorkWithMixedProgress:hud];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [hud hideAnimated:YES];
                });
            });
            break;
        }
        default:
            break;
    }
}

-(void) showProgress4:(NSInteger)row {
    switch (row) {
        case 0:{
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view.window animated:YES];
            [self dismissAfter:hud];
            
            break;
        }
        case 1:{
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
            hud.mode = MBProgressHUDModeDeterminate;
            hud.label.text = NSLocalizedString(@"Loading...", @"HUD loading title");
            // Set up NSProgress
            NSProgress *progressObject = [NSProgress progressWithTotalUnitCount:100];
            hud.progressObject = progressObject;
            // Configure a cancel button.
            [hud.button setTitle:NSLocalizedString(@"Cancel", @"HUD cancel button title") forState:UIControlStateNormal];
            [hud.button addTarget:progressObject action:@selector(cancel) forControlEvents:UIControlEventTouchUpInside];
            
            dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
                // Do something useful in the background and update the HUD periodically.
                [self doSomeWorkWithProgressObject:progressObject];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [hud hideAnimated:YES];
                });
            });
            
            break;
        }
        case 2:{
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
            hud.backgroundView.style = MBProgressHUDBackgroundStyleSolidColor;
            hud.backgroundView.color = [UIColor colorWithWhite:0.f alpha:0.1f];
            
            [self dismissAfter:hud];
            break;
        }
        case 3:{
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
            hud.contentColor = [UIColor colorWithRed:0.f green:0.6f blue:0.7f alpha:1.f];
            hud.label.text = NSLocalizedString(@"Loading...", @"HUD loading title");
            
            [self dismissAfter:hud];
            break;
        }
        default:
            break;
    }
}



-(void) dismiss:(MBProgressHUD *)hud {
    [hud hideAnimated:YES];
}

-(void) dismissAfter:(MBProgressHUD *)hud {
    dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
        //sleep
        sleep(2);
        //main queue
        dispatch_async(dispatch_get_main_queue(), ^{
            [hud hideAnimated:YES];
        });
    });
}

-(void) dismissAfter2:(MBProgressHUD *)hud {
    [hud hideAnimated:YES afterDelay:2.f];
}

-(void) dismissProgressAfter:(MBProgressHUD *)hud {
    dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
        //sleep
        [self doSomeWorkWithProgress];
        //main queue
        dispatch_async(dispatch_get_main_queue(), ^{
            [hud hideAnimated:YES];
        });
    });
}

-(void) dismissProgressAfter2:(MBProgressHUD *)hud {
    dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
        [self doSomeWorkWithMixedProgress:hud];
        //main queue
        dispatch_async(dispatch_get_main_queue(), ^{
            [hud hideAnimated:YES];
        });
    });
}

- (void)doSomeWorkWithProgress {
    self.canceled = NO;
    float progress = 0.0f;
    while (progress < 1.0f) {
        if (self.canceled)
            break;
        progress += 0.01f;
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD HUDForView:self.navigationController.view].progress = progress;
        });
        usleep(50000);
    }
}

- (void)doSomeWorkWithMixedProgress:(MBProgressHUD *)hud {
    // Indeterminate mode
    sleep(2);
    // Switch to determinate mode
    dispatch_async(dispatch_get_main_queue(), ^{
        hud.mode = MBProgressHUDModeDeterminate;
        hud.label.text = NSLocalizedString(@"Loading...", @"HUD loading title");
    });
    float progress = 0.0f;
    while (progress < 1.0f) {
        progress += 0.01f;
        dispatch_async(dispatch_get_main_queue(), ^{
            hud.progress = progress;
        });
        usleep(50000);
    }
    // Back to indeterminate mode
    dispatch_async(dispatch_get_main_queue(), ^{
        hud.mode = MBProgressHUDModeIndeterminate;
        hud.label.text = NSLocalizedString(@"Cleaning up...", @"HUD cleanining up title");
    });
    sleep(2);
    dispatch_sync(dispatch_get_main_queue(), ^{
        UIImage *image = [[UIImage imageNamed:@"icon_home"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
        hud.customView = imageView;
        hud.mode = MBProgressHUDModeCustomView;
        hud.label.text = NSLocalizedString(@"Completed", @"HUD completed title");
    });
    sleep(2);
}

- (void)doSomeWorkWithProgressObject:(NSProgress *)progressObject {
    // This just increases the progress indicator in a loop.
    while (progressObject.fractionCompleted < 1.0f) {
        if (progressObject.isCancelled) break;
        [progressObject becomeCurrentWithPendingUnitCount:1];
        [progressObject resignCurrent];
        usleep(50000);
    }
}

- (void)cancelWork:(id)sender {
    self.canceled = YES;
}


@end
